package com.sgb.goods.view.adapter.publish;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.goods.BR;
import com.sgb.goods.R;
import com.sgb.goods.databinding.GoodsItemImageBinding;
import com.sgb.goods.entity.AlbumEntity;
import com.sgb.goods.utils.base.GoodsSdk;
import com.sgb.goods.utils.base.adapter.BaseCommonAdapter;
import com.sgb.goods.utils.module.GoodsModule;
import com.sgb.goods.view.activity.GoodsPublishActivity;
import com.swgk.core.util.GlideEngine;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ImageAdapter extends BaseCommonAdapter<AlbumEntity> {

    /** 默认的添加视图item */
    public AlbumEntity defaultItem = new AlbumEntity(true);
    /**
     * 选择图片后返回的LocalMedia
     **/
    private List<LocalMedia> mData = new ArrayList<>();
    /**
     * 用于图片预览的本地图片地址集合，这个预览一定要去优化
     **/
    private List<String> preViewList = new ArrayList<>();
    /**
     * 上传图片的最大张数
     **/
    private int maxSize;
    public ISelectPop iSelectPop;

    public interface ISelectPop {
        void openPop();
    }

    public void OnSelectPop(ISelectPop iSelectPop) {
        this.iSelectPop = iSelectPop;
    }

    public ImageAdapter(int maxSize) {
        super(R.layout.goods_item_image, BR.viewModel);
        super.addData(defaultItem);
        this.maxSize = maxSize;
    }

    @Override
    protected void convert(BaseViewHolder baseHolder, ViewDataBinding dataBinding, AlbumEntity entity) {
        GoodsItemImageBinding mDataBinding = (GoodsItemImageBinding) dataBinding;
        if(null != entity.imageUrl) {
            //加载网络图片与本地图片
            Glide.with(mContext).load(entity.imageUrl).into(mDataBinding.first.photoImg);
            // 查看图片
            mDataBinding.first.photoImg.setOnClickListener(view -> openPhotoView(baseHolder.getLayoutPosition()));
            // 删除图片
            mDataBinding.first.deleteImg.setOnClickListener(v -> {
                mData.remove(getData().indexOf(entity) - 1);
                preViewList.remove(getData().indexOf(entity) - 1);
                getData().remove(entity);
                notifyDataSetChanged();
            });
        }

        if(mDataBinding.second.getRoot().getVisibility() == View.VISIBLE) {
            mDataBinding.second.addRl.setOnClickListener(v -> {
                if(null != iSelectPop) {
                    iSelectPop.openPop();
                }
            });
            // 如果item个数==展示最大数量缩略图，那么隐藏添加视频的入口
            mDataBinding.second.getRoot().setVisibility(getItemCount() == maxSize + 1 ? View.GONE : View.VISIBLE);
        }
    }

    public int getDataSize() {
        return Math.max(getData().size() - 1, 0);
    }

    @Override
    public void addData(@NonNull @NotNull AlbumEntity data) {
        sort();
        super.addData(data);
        super.addData(defaultItem);
    }

    public void setData(List<LocalMedia> data) {
        sort();
        List<AlbumEntity> dataList = convertDataToAlbumEntity(data, true);
        dataList.add(defaultItem);
        super.setNewData(dataList);
        notifyDataSetChanged();
    }

    @Override
    public void setNewData(@Nullable @org.jetbrains.annotations.Nullable List<AlbumEntity> data) {
        sort();
        if(null != data) {
            data.add(defaultItem);
        }
        super.setNewData(data);
    }

    @Override
    public void addData(@NonNull @NotNull Collection<? extends AlbumEntity> newData) {
        sort();
        super.addData(newData);
        super.addData(defaultItem);
    }

    /** 默认的添加视图排序 */
    private void sort() {
        int index = getData().indexOf(defaultItem);
        if(-1 != index) {
            getData().remove(defaultItem);
            notifyItemChanged(index);
        }
    }

    /** 转换图片数据 */
    public List<AlbumEntity> convertDataToAlbumEntity(List<LocalMedia> oldData, boolean isCompressPath) {
        // 清除数据，保证用户所选图片不会重复
        getData().clear();
        // 转换适配器数据源，这里应该可以优化？
        List<AlbumEntity> newData = new ArrayList<>(oldData.size());
        for(LocalMedia localMedia : oldData) {
            AlbumEntity entity = new AlbumEntity();
            entity.imageUrl = isCompressPath ? localMedia.getCompressPath() : localMedia.getPath();
            newData.add(entity);
            preViewList.add(entity.imageUrl);
        }
        // 清理复选用户本次发布页面中上次或者之前已选中过的图片
        mData.clear();
        mData.addAll(oldData);
        return newData;
    }

    /**
     * 设置网络图片List
     */
    public void setNetImgList(List<String> netImgList) {
//        if (netImgList == null) {
//            this.neImgList = new ArrayList<>();
//        } else {
//            this.neImgList = new ArrayList<>(netImgList);
//            this.urls.addAll(netImgList);
//        }
//        notifyDataSetChanged();
    }

    /**
     * 删除重复的网络图片List
     * 有点问题(取消后从网络图库中取消不会取消)
     */
    public void updateNetImgList() {

    }

    /**
     * 预览
     **/
    private void openPhotoView(int position) {
        GoodsModule.getInstance().call1("photoPreView", preViewList, position);
    }

    /**
     * 打开相册
     */
    public void openAlbum() {
        PictureSelector.create(GoodsSdk.getInstance().getTopActivity())
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .maxSelectNum(maxSize)//判断还能选多少张图片
                .isCompress(true)//是否压缩
                .minimumCompressSize(200)//小于200kb不压缩
                .selectionMedia(mData)
                .forResult(GoodsPublishActivity.IMAGE_ADAPTER_LIST);
    }
}